import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Modal,
  message,
  Badge,
  Divider,
  Table,
  Popconfirm,
  Radio,
  TreeSelect,
  Icon,
  Menu,
  Dropdown,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Add from './DatabaseGroup/add';
import Edit from './DatabaseGroup/edit';
import Detail from './DatabaseGroup/detail';
import styles from '../search.less';
const FormItem = Form.Item;
const statusMap = ['success', 'error'];
const status = ['启用', '禁用'];

@Form.create()
/* eslint react/no-multi-comp:0 */
@connect(
  state => ({
    loadingqueryDbGroupList: state.loading.effects['databaseGroup/queryDbGroupList'],
    dataqueryDbGroupList: state.databaseGroup.dataqueryDbGroupList,
    // dataqueryList: state.databaseGroup.dataqueryList,
  }),
  dispatch => ({
    queryDbGroupList: e => dispatch({ type: 'databaseGroup/queryDbGroupList', payload: e }),
    dbgroupdelete: e => dispatch({ type: 'databaseGroup/dbgroupdelete', payload: e }),
    // queryList: e => dispatch({ type: 'databaseGroup/queryList', payload: e }),
  })
)
@Form.create()
class DatabaseGroup extends PureComponent {
  state = {
    selectedRows: [],
  };

  columns = [
    {
      title: '数据库组名',
      dataIndex: 'groupName',
    },
    {
      title: '数据库组管理员',
      dataIndex: 'adminUserCode',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis:true,
      width:'40%',
    },
    {
      title: '操作',
      width:140,
      render: (text, record) => (
        <Fragment>
          <Detail text={record}><a>详情</a></Detail>
          <Divider type="vertical" />
          <Edit text={record} pageList={this.pageList}><a>编辑</a></Edit>
          <Divider type="vertical" />
          <a onClick={() => this.deleteData(text.id)}>删除</a>
        </Fragment>
      ),
    },
  ];

  // 删除方法
  deleteData = id => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleThisRowDelete(id),
    });
  };

  batchDelete = (rows = []) => {
    const ids = rows
      .map(item => {
        return item.id;
      })
      .join(',');
    this.deleteData(ids); //批量删除
  };

  handleThisRowDelete = id => {
    return this.props.dbgroupdelete({ ids: id }).then(res => {
      if (res.result == 'ok') {
        Modal.success({ title: res.msg });
        this.pageList();
        this.setState({ selectedRows: [] });
      } else {
        Modal.error({ title: '操作失败', content: res.msg });
      }
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  // 分页查询列表
  pageList = (data, pageSize = 10, pageNum = 0) => {
    const { dispatch } = this.props;
    const values = {
      groupName: (data && data.groupName) || '',
      adminUserCode: (data && data.adminUserCode) || '',
      pageSize: pageSize,
      pageNum: pageNum,
    };
    this.props.queryDbGroupList(values);
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  }; //重置
  componentDidMount() {
    this.pageList();
    // this.props.queryList();
    // this.getTree();
    // this.adminMothod();
  }

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      //点击查询
      this.setState({
        formValues: fieldsValue,
      });
      this.pageList(fieldsValue);
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="数据库组名">
              {getFieldDecorator('groupName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          {/*<Col md={8} sm={24}>*/}
          {/*  <FormItem label="数据库组管理员">*/}
          {/*    {getFieldDecorator('adminUserCode')(*/}
          {/*     <Select*/}
          {/*     placeholder="请选择"*/}
          {/*     style={{ width: '100%' }}*/}
          {/*     loading={this.props.loadingqueryList}*/}
          {/*     showSearch*/}
          {/*   >*/}
          {/*     {this.props.dataqueryList.map(v => {*/}
          {/*       return (*/}
          {/*         <Option key={v.userId} value={v.userCode}>*/}
          {/*           {v.userCode}/{v.userName}*/}
          {/*         </Option>*/}
          {/*       );*/}
          {/*     })}*/}
          {/*   </Select>*/}
          {/*    )}*/}
          {/*  </FormItem>*/}
          {/*</Col>*/}

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  handleStandardTableChange(pagination, filters, sorter) {
    const { formValues } = this.state;
    // 分页请求
    this.pageList(formValues, pagination.pageSize, pagination.current - 1);
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    return (
      <PageHeaderWrapper title="数据库组">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Add pageList={this.pageList}>
                <Button icon="plus" type="primary">
                  新增
                </Button>
              </Add>
              {this.state.selectedRows.length > 0 && (
                <span>
                  <Button onClick={() => this.batchDelete(this.state.selectedRows)}>
                    批量删除
                  </Button>
                </span>
              )}
            </div>
            <TableList
              className={styles.tdPadding}
              selectedRows={this.state.selectedRows}
              loading={this.props.loadingqueryDbGroupList}
              data={this.props.dataqueryDbGroupList}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange.bind(this)}
              rowKey={record => record.id}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default DatabaseGroup;
